package com.zh.common.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.AttributeSet
import android.view.View
import androidx.annotation.RequiresApi
import com.zh.common.R

/**
 * @auth zh
 * @time 2022/1/21 - 15:55
 * @desc 不规则图片进度（男女比列那种）
 */
@RequiresApi(Build.VERSION_CODES.M)
class PixelsPicsView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint()
    private var defaultProgress = 0f//默认进度
    private var pictureDrawable: Drawable? = null//需要的底图
    private var color = 0//需要着色的颜色值

    private var pictureBitmap: Bitmap
    private var bitmap: Bitmap? = null
    private var mWidth = 0
    private var mHeight = 0
    private var pixels: IntArray? = null//记录图片坐标数组

    /**
     * 设置进度: 0~1
     */
    fun setProgress(value: Float) {
        defaultProgress = if (value > 1) 1f else value
        invalidate()
    }

    init {
        paint.isAntiAlias = true
        paint.style = Paint.Style.FILL
        val typedArray =
            context.obtainStyledAttributes(attrs, R.styleable.PixelsPicsView, defStyleAttr, 0)
        color = typedArray.getColor(
            R.styleable.PixelsPicsView_ppv_color, context.getColor(R.color.colorPrimary)
        )
        pictureDrawable = typedArray.getDrawable(R.styleable.PixelsPicsView_ppv_picture)
        defaultProgress =
            typedArray.getFloat(R.styleable.PixelsPicsView_ppv_default_progress, 0f)
        pictureBitmap = (pictureDrawable as BitmapDrawable).bitmap
        typedArray.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(pictureBitmap.width, pictureBitmap.height)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mWidth = w
        mHeight = h
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        //设置图片大小
        if (!pictureBitmap.isRecycled) {
            pictureBitmap = resizeImage(pictureBitmap, mWidth, mHeight)
            //得到图片像素坐标
            pixels = IntArray(mWidth * mHeight)
            pictureBitmap.getPixels(pixels, 0, mWidth, 0, 0, mWidth, mHeight)
            //绘制背景图片
            canvas?.drawBitmap(pictureBitmap, 0f, 0f, null)
            //设置需要绘制的图片像素坐标
            bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888)
            bitmap?.setPixels(
                pixels,                                                  // 设置像素数组，对应点的像素被放在数组中的对应位置，像素的argb值全包含在该位置中
                mWidth * (mHeight * (1 - defaultProgress)).toInt(),// 设置偏移量，我们截图的位置就靠此参数的设置
                mWidth,                                                  // 设置一行打多少像素，通常一行设置为bitmap的宽度
                0,                                                     // 设置开始绘图的x坐标
                (mHeight * (1 - defaultProgress)).toInt(),               // 设置开始绘图的y坐标
                mWidth,                                                  // 设置绘制出图片的宽度
                (mHeight * defaultProgress).toInt()                      // 设置绘制出图片的高度
            )
            paint.colorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)
            canvas?.drawBitmap(bitmap!!, 0f, 0f, paint)
            bitmap!!.recycle()
        }
    }

    //设置宽高
    private fun resizeImage(bitmap: Bitmap, width: Int, height: Int): Bitmap {
        val bmpWidth = bitmap.width
        val bmpHeight = bitmap.height
        val scaleWidth = width.toFloat() / bmpWidth
        val scaleHeight = height.toFloat() / bmpHeight
        val matrix = Matrix()
        matrix.postScale(scaleWidth, scaleHeight)
        return Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true)
    }
}